<template>
  <div>
    <div style="width: 2.85rem" @click="clickFile(item)">
      <div class="learning-card">
        <div class="read-status flex-center" v-show="item.readStatus == 0">
          <span style="font-size: 0.15rem">未查阅</span>
        </div>
        <div style="width: 2.85rem; height: 1.7rem">
          <!-- 封面 -->
          <img
            class="w-full h-full"
            data-enable-preview="false"
            :src="`${item.coverUrl}?v=${Date.now()}`"
            v-if="!isOffLine && item.coverUrl && item.fileType != 5"
          />
          <div class="w-full h-full flex-center" v-else>
            <div class="w-full h-full">
              <div class="w-full h-full flex justify-center items-center box-border">
                <!-- photo -->
                <template v-if="suffixFilter(item.fileUrl)['value'] == 2">
                  <div>
                    <el-image
                      :src="
                        $store.state.learning.minioConfig.fileServerUrlApp +
                        '/' +
                        (item.isSystemFile == 0
                          ? 'snd-ai-assistant'
                          : $store.state.learning.minioConfig.bucket) +
                        item.fileUrl
                      "
                      :preview-src-list="[
                        $store.state.learning.minioConfig.fileServerUrlApp +
                          '/' +
                          (item.isSystemFile == 0
                            ? 'snd-ai-assistant'
                            : $store.state.learning.minioConfig.bucket) +
                          item.fileUrl
                      ]"
                      :id="'image' + item.id"
                      style="width: 2.85rem; height: 1.7rem"
                    />
                  </div>
                </template>
                <!-- video -->
                <template v-else-if="suffixFilter(item.fileUrl)['value'] == 3">
                  <img class="w-full h-full" :src="item.thumbnail" />
                </template>
                <!-- audio -->
                <template v-else-if="suffixFilter(item.fileUrl)['value'] == 5">
                  <div :id="'audio' + item.id" class="flex" :class="'audio' + item.id">
                    <div class="flex-center">
                      <img
                        class="ml-16px"
                        :src="suffixFilter(item.fileUrl)['url']"
                        style="width: 0.6rem; height: 0.6rem"
                      />
                    </div>
                    <div
                      class="text-333 font-medium text-center overflow-hidden ml-12px mr-16px"
                      style="
                        min-width: 1.37rem;
                        max-width: 1.81rem;
                        font-size: 0.18rem;
                        line-height: 0.24rem;
                        text-align: center;
                        word-break: break-all;
                      "
                    >
                      <div style="text-align: left">
                        <div class="flex justify-center">
                          <span
                            style="
                              display: -webkit-box;
                              -webkit-line-clamp: 4;
                              -webkit-box-orient: vertical;
                              overflow: hidden;
                            "
                          >
                            {{ item.fileName + item.fileUrl.slice(item.fileUrl.lastIndexOf('.')) }}
                          </span>
                        </div>
                      </div>
                      <div class="mb-4px">
                        <el-progress
                          color="rgba(81, 195, 255, 1)"
                          define-back-color="rgba(230, 241, 255, 1)"
                          :percentage="percentage"
                          :format="() => {}"
                        ></el-progress>
                      </div>
                      <div class="flex justify-center">
                        <div style="color: rgba(163, 163, 163, 1)">
                          {{ currentTimeFilter }}
                        </div>
                        <div class="mx-10px">
                          <img
                            :src="
                              !status
                                ? require('@/assets/learning/bofang.png')
                                : require('@/assets/learning/zanting.png')
                            "
                            style="height: 0.22re; width: 0.22rem"
                            @click.stop="start(item)"
                          />
                        </div>
                        <div class="text-A3A3A3">
                          {{ durationFilter }}
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
                <!-- other -->
                <template v-else>
                  <div>
                    <img
                      :src="suffixFilter(item.fileUrl)['url']"
                      class="ml-16px"
                      style="width: 0.6rem; height: 0.6rem"
                    />
                  </div>
                  <div
                    class="text-333 font-medium text-center overflow-hidden ml-12px mr-16px"
                    style="
                      max-width: 1.81rem;
                      font-size: 0.18rem;
                      line-height: 0.24rem;
                      text-align: left;
                      display: -webkit-box;
                      -webkit-line-clamp: 4;
                      -webkit-box-orient: vertical;
                      overflow: hidden;
                      text-align: left;
                      word-break: break-all;
                    "
                  >
                    {{ item.fileName + item.fileUrl.slice(item.fileUrl.lastIndexOf('.')) }}
                  </div>
                </template>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- fileName -->
      <div
        class="overflow-hidden text-center mt-10px text-A3A3A3"
        style="font-size: 0.18rem; width: 2.85rem; white-space: nowrap; text-overflow: ellipsis"
      >
        {{ item.fileName + item.fileUrl.slice(item.fileUrl.lastIndexOf('.')) }}
      </div>
    </div>
  </div>
</template>

<script>
import { determineType } from '../fileType.js'
import ppt from '@/assets/learning/ppt@2x.png'
import xlsx from '@/assets/learning/xlsx@2x.png'
import pdf from '@/assets/learning/pdf@2x.png'
import photo from '@/assets/learning/photo@2x.png'
import vedio from '@/assets/learning/video@2x.png'
import word from '@/assets/learning/word@2x.png'
import audio from '@/assets/learning/audio@2x.png'
import other from '@/assets/learning/other@2x.png'
import { isHaveNetwork } from '@/utils'

export default {
  components: {},
  props: {
    id: {
      type: String
    },
    item: {
      type: Object
    },
    audioUrl: {
      type: String
    }
  },
  data() {
    return {
      isOffLine: false,
      show: false,
      isFull: false,
      // id: '',
      context: null,
      currentTime: 0,
      duration: 0,
      durationFilter: '00:00',
      currentTimeFilter: '00:00',
      status: false, // 音频是否是暂停、播放状态
      isPreviewImage: 0, // 图片是否是预览状态
      isAudioPlayed: false,
      videoData: null
    }
  },
  computed: {
    percentage() {
      const { currentTime, duration } = this

      if (!currentTime || !duration) return 0

      const percentage = (currentTime.toFixed(0) / duration.toFixed(0)) * 100
      return percentage
    }
  },
  created() {
    if (!isHaveNetwork()) {
      this.isOffLine = true
    }

    const { fileType, isSystemFile } = this.item
    if (fileType == 5) {
      const url = this.$store.state.learning.minioConfig.fileServerUrlApp
      const bucket =
        isSystemFile == 0 ? 'snd-ai-assistant' : this.$store.state.learning.minioConfig.bucket
      const fileUrl = this.$props.item.fileUrl
      // 音频
      this.context = document.createElement('audio')
      // 'https://bjetxgzv.cdn.bspapp.com/VKCEYUGU-hello-uniapp/2cc220e0-c27a-11ea-9dfb-6da8e309e0d8.mp3'
      this.context.src = `${url}/${bucket}${fileUrl}`
      this.onTimeUpdate()
      this.onCanplay()
      this.onEnded()
    }
  },
  // watch: {
  // 	isFull() {
  // 		this.$emit('on-play', { isFull: this.isFull, item: this.videoData });
  // 	}
  // },
  methods: {
    // 判断进入退出全屏
    checkIsFullScreen() {
      var isFullScreen =
        document.fullscreen || document.mozFullScreen || document.webkitIsFullScreen
      return isFullScreen == undefined ? false : isFullScreen
    },
    // 全屏
    Screen(element) {
      if (element.requestFullscreen) {
        element.requestFullscreen()
      } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen()
      } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen()
      } else if (element.oRequestFullscreen) {
        element.oRequestFullscreen()
      } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullScreen()
      } else {
        var requestFullscreen =
          document.documentElement.requestFullscreen ||
          document.documentElement.webkitRequestFullscreen ||
          document.documentElement.mozRequestFullscreen ||
          document.documentElement.requestFullScreen ||
          document.documentElement.webkitRequestFullScreen ||
          document.documentElement.mozRequestFullScreen
        if (requestFullscreen) {
          requestFullscreen.call(document.documentElement)
        }
        // ios不处理，自动就会全屏
        // element.play()
      }
    },
    exitScreen(element) {
      if (document.exitFullscreen) {
        document.exitFullscreen()
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen()
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen()
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen()
      }
    },
    getAssetUrl(value) {
      let urls = {
        7: ppt,
        0: xlsx,
        1: pdf,
        2: photo,
        3: vedio,
        4: word,
        5: audio,
        6: other
      }

      return urls[value]
    },
    suffixFilter(fileUrl) {
      const i = fileUrl.lastIndexOf('.')
      const suffix = fileUrl.slice(i + 1)
      const value = determineType(suffix)
      const url = this.getAssetUrl(value)
      return { url: url, value: value }
    },
    clickFile(item) {
      const { fileType } = item

      switch (fileType) {
        case 3:
          // video
          this.play(item.id, item)
          break
        case 5:
          // audio
          this.start(item)
          if (this.status) {
            this.$emit('on-click', { readStatus: 1, item: item })
          } else {
            this.$emit('on-click', { readStatus: 2, item: item })
          }
          break
        default:
          this.$emit('on-click', { readStatus: 1, item: item })
          break
      }
    },
    // video
    fullscreenchange(value, item) {
      this.isFull = !this.isFull
      var v = document.getElementById('video' + value)
      let v1 = v.querySelectorAll('video')[0]
      if (this.isFull) {
        v1.play()
      } else {
        v1.pause()
      }
    },
    playVideo(id) {
      this.id = id
      const v = document.getElementById('video' + id)
      v.play()
    },
    pauseVideo(id) {
      this.id = id
      const v = document.getElementById('video' + id)
      v.pause()
    },
    play(value, item) {
      const { android_call } = window

      if (android_call) {
        const onEnded = () => {
          this.$emit('on-click', { readStatus: 2, item: item })
        }

        const url =
          this.$store.state.learning.minioConfig.fileServerUrlApp +
          '/' +
          (item.isSystemFile == 0
            ? 'snd-ai-assistant'
            : this.$store.state.learning.minioConfig.bucket) +
          item.fileUrl
        const fileName = item.fileName + item.fileUrl.slice(item.fileUrl.lastIndexOf('.'))
        const callBackName = `fn${new Date().getTime()}`
        window.android_call[callBackName] = onEnded.bind(this)
        android.openVideo(url, fileName, callBackName)
        this.$emit('on-click', { readStatus: 1, item: item })
      } else {
        this.id = value
        this.videoData = item

        const video = document.getElementById('video' + this.id)
        video.addEventListener('play', () => {
          this.$emit('on-click', { readStatus: 1, item: item })
        })
        video.addEventListener('pause', () => {
          this.$emit('on-click', { readStatus: 2, item: item })
        })
        this.Screen(video)
        video.play()
      }
    },
    // audio
    start(item) {
      // 点击播放
      let audioId = item.id
      this.isAudioPlayed = true
      if (this.status) {
        this.context.pause()
        this.status = !this.status
        this.$emit('on-click', { readStatus: 2, item: item })
      } else {
        // uni.$emit('stop', item.id);
        this.context.play()
        this.status = !this.status
        this.$emit('on-click', { readStatus: 1, item: item })
        this.$emit('on-play-audio', {
          context: this,
          id: audioId,
          item
        })
      }
    },
    getSFM(seconds, dateFormat = 'H:i:s') {
      var obj = {}
      obj.H = Number.parseInt(seconds / 3600)
      obj.i = Number.parseInt((seconds - obj.H * 3600) / 60)
      obj.s = Number.parseInt(seconds - obj.H * 3600 - obj.i * 60)
      if (obj.H < 10) {
        obj.H = '0' + obj.H
      }
      if (obj.i < 10) {
        obj.i = '0' + obj.i
      }
      if (obj.s < 10) {
        obj.s = '0' + obj.s
      }

      // 3.解析
      let rs = dateFormat.replace('H', obj.H).replace('i', obj.i).replace('s', obj.s)
      const index = rs.indexOf(':')
      if (obj.H < 1) {
        rs = rs.slice(index + 1)
      }
      return rs
    },
    onCanplay() {
      // 进入可播放状态
      this.context.addEventListener('canplay', () => {
        this.$nextTick(() => {
          this.duration = this.context.duration
          this.durationFilter = this.getSFM(this.duration)
        })
      })
    },
    onTimeUpdate() {
      // 音频播放进度
      this.context.addEventListener('timeupdate', () => {
        if (!Number.isFinite(this.context.duration)) {
          this.duration = this.context.currentTime + 10
          this.currentTime = this.context.currentTime
        } else {
          this.duration = this.context.duration
          this.currentTime = this.context.currentTime
        }
        this.currentTimeFilter = this.getSFM(this.currentTime)

        this.durationFilter = this.getSFM(this.duration)
      })
    },
    onEnded() {
      // 播放结束
      this.context.addEventListener('ended', () => {
        this.status = false
        this.currentTime = 0
        this.currentTimeFilter = '00:00'
      })
    },
    changeAudio(e) {
      // 进度条方法
      let paused = this.context.paused
      this.context.pause()
      this.context.seek(e.detail.value)
      if (!paused) {
        this.context.play()
      }
    },
    getData() {
      return this.isAudioPlayed
    }
  }
}
</script>

<style lang="scss" scoped>
.learning-card {
  width: 285px;
  height: 170px;
  background: white;
  border: 1px solid #e6f1ff;
  position: relative;
}

.read-status {
  width: 63px;
  height: 24px;
  background-color: rgba(255, 64, 64, 1);
  border-radius: 0px 0px 0px 8px;
  position: absolute;
  right: 0px;
  top: 0px;
  text-align: center;
  color: white;
  z-index: 2;
}

video {
  width: 100%;
  height: 100%;
  object-fit: fill;
}

.uni-page {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1999;
  background-color: #000;
}

uni-slider {
  margin: 0px !important;
}

uni-slider .uni-slider-tap-area {
  padding: 0px !important;
}
</style>
